package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.LecturefileMapper;
import com.hbnu.system.model.entity.Lecturefile;
import com.hbnu.system.service.ILecturefileService;
import com.hbnu.system.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.BindException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * (Paperfile)表服务实现类
 *
 * @author makejava
 * @since 2023-08-15 13:46:42
 */
@Service
public class LecturefileServiceImpl extends ServiceImpl<LecturefileMapper, Lecturefile> implements ILecturefileService {
    @Autowired
    FileUploadUtil fileUploadUtil;
    @Override
    public boolean addLecturefile(Lecturefile lecturefile) {
        lecturefile.setFiledate(LocalDateTime.now());
        return baseMapper.insert(lecturefile)==1;
    }

    @Override
    public Lecturefile getLecturefile(String id) {
        Lecturefile lecturefile = super.getOne(Wrappers.lambdaQuery(Lecturefile.class)
                .eq(Lecturefile::getFileid,id));
        if(Objects.isNull(lecturefile)){
            throw new BaseException("文件编号异常!未查找到该文件信息");
        }
        return lecturefile;
    }

    @Override
    public List<Lecturefile> pageLecturefile(String id) {
        if(StrUtil.isBlank(id)){
            throw new BaseException("学术讲座编号为空值");
        }
        List<Lecturefile> lecturefileList = baseMapper.selectList(Wrappers.lambdaQuery(Lecturefile.class)
                .eq(Lecturefile::getLectureid,id));
        return lecturefileList;
    }

    @Override
    public boolean deletLecturefile(String id) throws IOException {
        Lecturefile one = super.getOne(Wrappers.lambdaQuery(Lecturefile.class)
                .eq(Lecturefile::getFileid, id));
        if (Objects.isNull(one)){
            throw new BaseException("文件编号有误!");
        }

        boolean delete = fileUploadUtil.delete(one.getFileurl());
        if(!delete){
            throw new BindException("附件删除失败");
        }
        return baseMapper.deleteById(id) == 1;
    }

    @Override
    public boolean updateLecturefile(Lecturefile lecturefile) {
        return baseMapper.updateById(lecturefile)==1;
    }
}

